<template>
  <div class="container">
    <div class="export-header">
      <el-button  icon="el-icon-edit" type="primary" size='medium' @click="addBtn">添加品牌</el-button>
    </div>
    <div class="input_modal">
      <div class="input-item">
        <span>品牌名：</span>
        <el-input v-model="brandName" placeholder="请输入内容" class="proName" @keyup.enter.native="search"></el-input>
      </div>
      <div class="input-item">
        <span>添加时间：</span>
         <el-date-picker
            v-model="dateArr"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
        </el-date-picker>
        <el-button icon="el-icon-search" type="primary" size="medium" @click="getList">查询</el-button>
      </div>
    </div>
    <div class="table_con">
      <el-table v-loading="loading" :data="tableData" :border='true'>
        <el-table-column :formatter="formatter" prop="sort" label="序号"></el-table-column>
        <el-table-column :formatter="formatter" prop="brandName" label="品牌名"></el-table-column>
        <el-table-column :formatter="formatter" prop="type" label="品牌类型">
          <template slot-scope="scope">
            {{scope.row.type == 'real'?'实物':'电子券'}}
          </template>
        </el-table-column>
        <el-table-column :formatter="formatter" prop="gmtCreated" label="添加时间"></el-table-column>
        <el-table-column :formatter="formatter" prop="isOpen" label="普通用户可看">
          <template slot-scope="scope">
            {{scope.row.isNormalUser == 'y'?'是':'否'}}
          </template>
        </el-table-column>
        <el-table-column :formatter="formatter" prop="isOpen" label="定制用户可看">
          <template slot-scope="scope">
            {{scope.row.isCustomUser == 'y'?'是':'否'}}
          </template>
        </el-table-column>
        <el-table-column width="280" prop="" label="操作">
          <template slot-scope="scope">
            <el-button @click="editBtn(scope.row)" type="primary" size="mini">编辑</el-button>
            <el-button icon="el-icon-delete" type="danger" size="mini" @click="deleteRole(scope.row.id)">删除</el-button>
             <el-button v-if="!scope.row.edit" @click="changeSort(scope.$index)" type="primary" size="mini">调整排序</el-button>
            <el-input style="width:60px;" v-model="scope.row.sortindex" v-if="scope.row.edit" placeholder=""></el-input>
            <el-button v-if="scope.row.edit" @click="handleSort(scope.$index)" type="primary" size="mini">确定</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="pageIndex" :page-size="pageSize" :page-sizes='[10,20,30,40]' layout="total, sizes, prev, pager, next, jumper" :total="pageCount">
      </el-pagination>
    </div>
    <el-dialog title="添加/编辑品牌" :visible.sync="dialogVisible" width="50%">
      <div class="tag-head">
        <el-form :model="user" :rules="rules" ref="user" label-width="120px" class="">
          <el-form-item label="品牌类型" prop="type">
            <el-select v-model='user.type' placeholder='-请选择-'  style="height: 30px;  line-height: 30px;width:200px;">
                <el-option
                  label="实物"
                  value="real">
                </el-option>
                <el-option
                  label="电子券"
                  value="virtual">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="品牌名" prop="papersName">
            <el-input style="width:200px" v-model="user.brandName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item
          label="所属城市："
          prop="city"
          >
              <el-select @change="provinceChange" v-model='user.provinceCode' placeholder='-请选择-'  style="height: 30px;  line-height: 30px;width:200px;">
                  <el-option label="全国" value="全省" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
                  <el-option v-for="(item,index) in provinceArr" :key="index" :label="item.ssqname" :value="item.ssqid" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
              </el-select>
              <el-select  v-if="user.provinceCode!='全省'" v-model='user.cityCodes' placeholder='-请选择-'  style="height: 30px;  line-height: 30px;width:200px;">
                  <!-- <el-option label="全部" value="" style="height: 30px;  line-height: 30px;width:200px;"></el-option> -->
                  <el-option v-for="(item,index) in cityArr" :key="index" :label="item.ssqname" :value="item.ssqid" style="height: 30px;  line-height: 30px;width:200px;"></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="品牌Logo" prop="photoIds">
            <el-upload
            class="avatar-uploader"
            :action="upLoadUrl"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
           >
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
            >
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            ></i>
          </el-upload>
          </el-form-item>
          <el-form-item label="普通用户可看" prop="isNormalUser">
            <el-select v-model='user.isNormalUser' placeholder='-请选择-'  style="height: 30px;  line-height: 30px;width:200px;">
                <el-option
                  label="是"
                  value="y">
                </el-option>
                <el-option
                  label="否"
                  value="n">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="定制用户可看" prop="isCustomUser">
            <el-select v-model='user.isCustomUser' placeholder='-请选择-'  style="height: 30px;  line-height: 30px;width:200px;">
                <el-option
                  label="是"
                  value="y">
                </el-option>
                <el-option
                  label="否"
                  value="n">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="品牌介绍" prop="introduction">
            <bg-editor
              id="applyShopMsg"
              :minHeight="300"
              :uploadUrl="upLoadUrl"
              :content="user.introduction"
              @editorData='editorInfo1'
          >
          </bg-editor>
          </el-form-item>
          <el-form-item label="适用门店" prop="introduction">
            <div>
              <el-switch
                v-model="user.isApplyShop"
                active-value="y"
                inactive-value="n">
              </el-switch>
              展示/不展示
            </div>
             <bg-editor
              id="shopIntroduction"
                :minHeight="300"
                :uploadUrl="upLoadUrl"
                :content="user.shopIntroduction"
                @editorData='editorInfo'
            >
            </bg-editor>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handSave('user')" type="primary">确 定</el-button>
        <el-button style="margin-right:30%" type="primary" @click="dialogVisible = false">返 回</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
let CONSTANT = require("../../constant/constant.js");
let common = require("../../common.js");
let countryArr = require("../../../static/city.json");
export default {
  data() {
    return {
      tableData: [],
      dateArr:[],
      dialogVisible:false,
      pageCount: null,
      pageIndex: 1,
      pageSize: 10,
      loading: true,
      brandName: null,
      imageUrl:null,
      upLoadUrl:'',
      rules:{},
      provinceArr :[],
      cityArr:[],
      user:{
          id:'',
          isOpen:'y',
          brandName:'',
          photoIds:'',
          type:"",
          introduction:'',
          isApplyShop:'n',
          isCustomUser:"",
          isNormalUser:'',
          shopIntroduction:'',
          provinceCode:'',
          cityCodes:''
      }
    };
  },
  components: {
    "bg-editor": () => import("../common/bg-editor.vue")
  },
  mounted() {
     this.provinceArr = countryArr.provinces.province
    this.pageIndex = this.$router.currentRoute.query.pageIndex
      ? this.$router.currentRoute.query.pageIndex
      : 1;
    this.getList();
  },
  methods: {
    provinceChange(){
        this.cityArr = []
        this.user.cityCodes = ''
        this.provinceArr.map(item=>{
            if(this.user.provinceCode == item.ssqid){
                this.cityArr = item.cities.city
            }
        })
    },
    editorInfo(e) {
       this.user.shopIntroduction = e
    },
    editorInfo1(e) {
       this.user.introduction = e
    },
    changeSort(index){
      this.tableData[index].edit = true
    },
    handleSort(index){
      let obj = this.tableData[index]
      let  url = CONSTANT.URL.LIST.brandAdjustSort;
      let param = {
        id:obj.id,
        sort:obj.sortindex
      } ;
      common.requestAjax(url,JSON.stringify(param),null,(res)=>{
          if(res.status == 200){
              this.$message({
                  type:'success',
                  message:'设置成功!'
              });
              this.getList()
          }
          else{
              this.$message({
                  type:'warning',
                  message:res.msg
              })
          }
      })  
    },
    beforeAvatarUpload(file) {
        let url = CONSTANT.URL.SYSTEM.UPLOADFILEBYCOS;
        let param = {
          suffix: file.name.split(".")[1], // 文件后缀  png
          contentType: file.type // 文件类型  image/png
        };
        console.log(param,'')
        common.requestAjax(url, null, param, res => {
          this.upLoadUrl = res.data.bussData.uploadUrl;
          common.uploadFile(this.upLoadUrl, file, file.type, res1 => {
           this.imageUrl = res.data.bussData.downloadUrl
           this.user.photoIds = res.data.bussData.fileKey
          })
        });
      },
    formatter(row, column, cellValue) {
      return cellValue ? cellValue : "- -";
    },
    addBtn(){
        this.user = {
            id:'',
            brandName:'',
            photoIds:'',
            type:'',
            isOpen:'y',
            introduction:'',
            isApplyShop:'n',
            isCustomUser:"",
            isNormalUser:'',
            shopIntroduction:'',
            provinceCode:'',
            cityCodes:''
        }
        this.cityArr = []
        setTimeout(()=>{
            $(`#applyShopMsg`).summernote('code','')
            $(`#shopIntroduction`).summernote('code','')
        },500)
        this.imageUrl = ''
        this.dialogVisible = true
    },  
    editBtn(obj){
      console.log(obj)
        this.user = {
            id:obj.id,
            brandName:obj.brandName,
            photoIds:obj.photos&&obj.photos.length?obj.photos[0].fileKey:'',
            type:obj.type,
            isOpen:obj.isOpen,
            introduction:obj.introduction||' ',
            isApplyShop:obj.isApplyShop,
            isCustomUser:obj.isCustomUser,
            isNormalUser:obj.isNormalUser,
            shopIntroduction:obj.shopIntroductionion||' ',
            provinceCode:obj.provinceCode,
            cityCodes:obj.cityCodes
        }
        this.provinceArr.map(item=>{
            if(obj.provinceCode == item.ssqid){
                this.cityArr = item.cities.city
            }
        })
        // if(!obj.introduction){
        //    $(`#applyShopMsg`).summernote('code','')
        // }
        // if(!obj.shopIntroduction){
        //    $(`#code`).summernote('code','')
        // }
       
        setTimeout(()=>{
            $(`#applyShopMsg`).summernote('code',obj.introduction)
            $(`#shopIntroduction`).summernote('code',obj.shopIntroduction||'')
        },500)
        this.imageUrl = obj.photos&&obj.photos.length?obj.photos[0].fileUrl:''
        this.dialogVisible = true
    },
    deleteRole:function(id) {
        this.$confirm('确定删除?', '提示', {           
            confirmButtonText: '确定',           
            cancelButtonText: '取消',           
            type: 'warning'         
        }).then(() => {           
            let  url = CONSTANT.URL.LIST.deleteEsBrand;
            let param = {id:id} ;
            common.requestAjax(url,JSON.stringify(param),null,(res)=>{
                if(res.status == 200){
                    this.$message({
                        type:'success',
                        message:'删除成功!'
                    });
                    this.getList();
                }
                else{
                    this.$message({
                        type:'warning',
                        message:res.msg
                    })
                }
            })      
        }).catch(() => {           
            this.$message({             
                type: 'info',             
                message: '已取消删除'           
            });                   
        });    
    },
    handSave(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let url = CONSTANT.URL.LIST.saveEsBrand;
          common.requestAjax(url, JSON.stringify(this.user), null, res => {
            if (res.status == 200) {
              this.$message({
                type: "success",
                message: "保存成功！"
              });
              this.getList();
              this.dialogVisible = false;
              this.user = {
                id:'',
                brandName:''
              };
            } else {
              this.$message({
                type: "warning",
                message: res.msg
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getList: function() {
        let endDate,beginDate;
        this.dateArr = this.dateArr?this.dateArr:[]
        if(this.dateArr.length){
            beginDate = this.dateArr[0]
            endDate = this.dateArr[1]
        }
      let url = CONSTANT.URL.LIST.findEsBrandByPage;
      let data = {
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        beginDate: beginDate,
        brandName: this.brandName,
        endDate: endDate
      };
      this.loading = true;
      common.requestAjax(url, JSON.stringify(data), null, res => {
        this.loading = false;
        let data = res.data;
        data.bussData.forEach((item,index)=>{
          item.sort = (this.pageIndex-1)*10+index+1
          item.edit = false
          item.sortindex = ''
        })
        this.tableData = data.bussData;
        this.pageCount = data.count;
      });
    },
    search: function(e) {
      if (e.keyCode == 13) {
        this.pageIndex = 1;
        this.getList();
      }
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageIndex = val;
      this.getList();
    }
  }
};
</script>
